package ext.tianma.part.processors;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.imported.CusImportBOM;
import ext.tianma.util.PropertiesUtil;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.part.WTPartUsageLink;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.OneOffVersionIdentifier;
import wt.vc.OneOffVersionInfo;
import wt.vc.VersionControlHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

public class ImportPartToParent extends DefaultObjectFormProcessor {
	private static final String CLASSNAME = CusImportBOM.class.getName();
	private static Logger log = LogR.getLogger(ImportPartToParent.class.getName());
	/** 模板路径 */
	private static String errorMessage = "";
	

	public static String sheetName = "D导出物料使用关系";
	public static String[] title = {"子料编号","子料视图","父料编号","客户型号"};
	public static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";

	@Override
	public FormResult doOperation(NmCommandBean nmCommandBean, List list) throws WTException {
		System.out.println("start import===>>>");
		errorMessage = "11";
		FormResult formresult = new FormResult();
		HttpServletRequest request = nmCommandBean.getRequest();

		if (request != null) {
			String[] parameter = request.getParameterValues("fileUrl");

			if (parameter == null) {
				return formresult;
			}

			String textName = parameter[0];

			if (textName != null) {
				// 判断是否为Excel文件类型
				if (!textName.endsWith(".xls") && !textName.endsWith(".xlsx")) {
					throw new WTException("选择的文件必须是Excel格式的文件");
				}
			}
			File file = (File) request.getAttribute("fileUrl");

			if (file != null) {
				String fileNumber = file.getAbsolutePath();

				if (fileNumber != null) {
					FileInputStream fis = null;
					Workbook wb = null;
					boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
					StringBuffer strBuf = new StringBuffer();
					try {
						fis = new FileInputStream(fileNumber);
						// 根据Excel文件的格式判断文件的解释方式为03或07（解析Excel兼容性）
						if (textName.endsWith(".xls")) {
							wb = new HSSFWorkbook(fis);
						} else if (textName.endsWith(".xlsx")) {
							wb = new XSSFWorkbook(fis);
						}
						Sheet sheet = wb.getSheetAt(0);
						;
						if (sheet != null) {

							Row row;
							Cell cell;
							Cell cell2;
							String partNumber = "";
							String partView = "";
							// 第一行为表头，从第二行开始遍历
							List<String> str = null;

							PropertiesUtil ut = new PropertiesUtil(configFilePath);
							String domain = ut.getValueByKey("system.domain");
							String folder = "TempExcel";
							WTProperties props = WTProperties.getLocalProperties();
							String filePath = props.getProperty("wt.codebase.location") + File.separator + "temp" + File.separator + folder + File.separator;
							File targerFile = new File(filePath);
							if(!targerFile.exists()) {
								targerFile.mkdir();
							}
							String pathAndName = filePath + "DCCStatementInquire1.xls";
							String realPath = domain + File.separator + "temp" + File.separator + folder + File.separator + "DCCStatementInquire1.xls";
							
							//1.创建HSSFWorkbook,对应一个excel
							
							HSSFWorkbook wb1 = new HSSFWorkbook();
							
							
							//2.在workbook中创建一个sheet，对应excel中的sheet
							HSSFSheet sheet1 = wb1.createSheet(sheetName);
							
							//3.在sheet中添加表头第0行
							HSSFRow row1 = sheet1.createRow(0);
							
							//4.创建单元格，并设置值表头 设置表头居中
						    HSSFCellStyle cellStyle = wb1.createCellStyle();
						    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
						    
						    // 声明列对象
						 	HSSFCell cell1 = null;
						 	
					 		// 创建标题
						 	
					 		for (int i = 0; i < title.length; i++) {
					 			cell1 = row1.createCell(i);
					 			cell1.setCellValue(title[i]);
					 			cell1.setCellStyle(cellStyle);
					 		}
					 		
					 		//创建内容
							int count = 0;
							for (int i = 0, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {

								if ((row = sheet.getRow(i)) != null) {
									cell = row.getCell(0);
									cell2 = row.getCell(1);
									row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
									row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
									partNumber = cell.getStringCellValue();
									partView = cell2.getStringCellValue();
									System.out.println("partNumber---->>>" + partNumber);
									System.out.println("partView---->>>" + partView);
									List<String> strs = new ArrayList<String>();
									if (partNumber != null && partView != null) {
									strs = 	getPartByParent(partNumber, partView);
									System.out.println("strList1===>>"+strs);
										if (strs!=null) {
											System.out.println("===22=="+strs.size());
											for (int k = 0; k < strs.size(); k++) {
												count ++;
												HSSFRow tempRow = sheet1.createRow(count + 1);
												String strMsg = strs.get(k);
												String childNumer = strMsg.substring(0, strMsg.indexOf("_"));
												String childView = strMsg.substring(strMsg.indexOf("_") + 1,
														strMsg.indexOf("|"));
												String parentNumer = strMsg.substring(strMsg.indexOf("|") + 1,
														strMsg.indexOf(";"));
												String parentCustomFactory = strMsg.split(";")[1];
												System.out.println("childNumer===>>" + childNumer);
												System.out.println("childView===>>" + childView);
												System.out.println("parentNumer===>>" + parentNumer);
												System.out.println("parentCustomFactory===>>" + parentCustomFactory);
												for (int l = 0; l <= 4; l++) {
													// 在一行内循环
													Cell first = tempRow.createCell(0);
													first.setCellValue(childNumer);

													Cell second = tempRow.createCell(1);
													second.setCellValue(childView);

													Cell third = tempRow.createCell(2);
													third.setCellValue(parentNumer);
													Cell four = tempRow.createCell(3);
													four.setCellValue(parentCustomFactory);
												}
											}
										}
									
									
									 System.out.println("strList2===>>"+str);
									}
								}
							}
							//调整每一列宽度自适应
					 		sheet1.autoSizeColumn((short)0); 
					        sheet1.autoSizeColumn((short)1); 
					        sheet1.autoSizeColumn((short)2); 
					        sheet1.autoSizeColumn((short)3);
						    
					        FileOutputStream os = new FileOutputStream(pathAndName);
					        wb1.write(os);
							os.flush();
							os.close();
//							 DCCWriteExcel.ecportExcel(str);
							 errorMessage = "导出成功！";
						}
					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						log.info("Debug   logs:");
						SessionServerHelper.manager.setAccessEnforced(flag);
					}

					if (strBuf.length() > 0) {
						log.info("Update Part Error : " + strBuf.toString());
						// throw new WTException("请根据错误信息检查导入数据");

					} else {
						log.info("==========>>>start import sucessful<<<=============");
					}
				}
			}
		}

		return formresult;
	}

	/***
	 * 导入bom方法
	 * 
	 * @param sheet
	 *            sheet页
	 * @param strBuf
	 *            返回错误信息
	 * @return
	 * @throws Exception
	 */
	private static String importBoms(Sheet sheet, StringBuffer strBuf) throws Exception {
		String strMesg = "";
		Iterator<Row> rowIterator = sheet.rowIterator();
		// 父件物料
		// 父物料编号----是否存在BOM结构
		Map<String, Boolean> numberflag = new HashMap<String, Boolean>();
		boolean flags = SessionServerHelper.manager.setAccessEnforced(false);
		List<String> stateList = new ArrayList<String>();
		try {
			while (rowIterator.hasNext()) {

			}
		} catch (Exception e) {
			log.info("--------exception3--------");
			throw new Exception(e.getLocalizedMessage());
		} finally {
			log.info("Debug   logs:");
			SessionServerHelper.manager.setAccessEnforced(flags);
		}
		return strMesg;
	}

	/**
	 * 根据部件编号获取所有最新小版本
	 * 
	 */
	public static List<WTPart> getAllLatestVersionPart(String number) {
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = getPart(part.getNumber(), v, part.getView().getName());
				if (null != p) {
					continue;
				}
				String version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
				System.out.println("view:" + part.getViewName() + "===version:" + version + "<br>");
				if (!list.contains(part)) {
					list.add(part);
				}
			}
		} catch (Exception e) {

		}
		return list;

	}

	/**
	 * 根据编号 版本 视图返回部件
	 * 
	 * @param num
	 * @param ver
	 * @param viewName
	 * @return
	 * @throws Exception
	 */
	public static WTPart getPart(String num, String ver, String viewName) throws Exception {
		if (viewName.equals(""))
			viewName = "Design";
		if (num == null || num.equals("") || num.trim().equals(""))
			return null;
		View view = ViewHelper.service.getView(viewName);
		WTPart part = null;
		QuerySpec qs = new QuerySpec(WTPart.class);
		SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, num);
		qs.appendWhere(sc);
		sc = new SearchCondition(WTPart.class, "view.key.id", SearchCondition.EQUAL,
				view.getPersistInfo().getObjectIdentifier().getId());
		qs.appendAnd();
		qs.appendWhere(sc);
		if (!ver.equals("")) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.versionida2versioninfo"),
					SearchCondition.EQUAL, new KeywordExpression("'" + ver + "'")));
		}
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
				new KeywordExpression("1")));

		qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			part = (WTPart) qr.nextElement();
			OneOffVersionInfo one = part.getOneOffVersionInfo();
			OneOffVersionIdentifier id = one.getIdentifier();
			String valueOneOff = id.getValue();
			if (valueOneOff == null)
				return part;
		}
		return part;
	}

	/**
	 * 通过物料A查找非直接关系的成品D 如：A-->B-->C-->D 通过A找到半成品B 再间接找到成品D B、D不存在直接关系
	 * 
	 * @param firstLevolmap
	 * @param array
	 *            显示的内容
	 * @param part
	 * @param basicpart
	 * @return
	 * @throws Exception
	 */
	public static List<String> FinishedGoodArray(Map<WTPart, ArrayList<WTPart>> firstLevolmap, JSONArray array,
			WTPart part, WTPart basicpart) throws Exception {
		List<String> str = new ArrayList<String>();
		if (firstLevolmap.containsKey(part)) {
			ArrayList<WTPart> finishedlist = firstLevolmap.get(part);
			for (WTPart halfpart : finishedlist) {
				// 类型
				String halfsofttype = GenericUtil.getTypeId(halfpart);
				String halfstate = halfpart.getState().getState().getDisplay(Locale.CHINA);
				if ("废弃".equals(halfstate)) {
					continue;
				}
				String partChildNumber = basicpart.getNumber();
				String partChildView = basicpart.getViewName();
				// 半成品存在相应的成品时
				// 成品属性
				if (halfsofttype.indexOf("cn.tianma.FinishedGood") != -1) {
					System.out.println("==========333333333333333333====" + halfpart.getNumber() + "--"
							+ halfpart.getViewName() + "===" + finishedlist.contains(halfpart));

					// 半成品属性

					String partParentNumber = halfpart.getNumber();
					String partParentView = halfpart.getViewName();
					String partParentCustomerName = (String) IBAUtil.getIBAValue(halfpart, "customerName");
					// 半成品属性

					String strMesg = partChildNumber + "_" + partChildView + "|" + partParentNumber + ";"
							+ partParentCustomerName;
					System.out.println("====searhMaterialPart  obj 111:" + strMesg);
					str.add(strMesg);

					// return array;
				} else {
					str = FinishedGoodArray(firstLevolmap, array, halfpart, basicpart);
				}
			}
		}

		return str;
	}

	public static List<String> getPartByParent(String number, String view) throws IOException, JSONException {
		
		System.out.println("==================MaterialReverseService.searhMaterialPart================:" + number);
		List<String> str = new ArrayList<String>();
//		if(strs!=null) {
//			str = strs;
//			System.out.println("===>>"+str);
//		}
		
		JSONArray array = new JSONArray();
		// 获取物料的全视图集合
		List<WTPart> list = new ArrayList<WTPart>();
		// 视图
		List<String> viewlist = new ArrayList<String>();
		WTPart basicpart = null;
		try {
			basicpart = CoreUtil.getWTPartByNumberAndView(number, "Design");
		} catch (WTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (StringUtil.isNullOrEmpty(view)) {
			list = getAllLatestVersionPart(number);

		} else {
			String[] views = view.split(",");
			try {
				for (String viewA : views) {
					WTPart part = getPart(number, "", viewA);
					if (part != null) {
						list.add(part);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		// 存放物料对应的父层 key - value集合 或半成品与成品对应的key - value集合 ,用于展示
		Map<WTPart, ArrayList<WTPart>> firstLevolmap = new HashMap<WTPart, ArrayList<WTPart>>();

		// 父层关系集合
		List<WTPart> parentlist = new ArrayList<WTPart>();

		for (WTPart part1 : list) {

			firstLevolmap = getParentParts3(part1, parentlist, firstLevolmap, list);
		}

		System.out.println("=============parentlist1111:" + parentlist.size());
		System.out.println("=============parentlist1111:" + parentlist.toString());
		System.out.println("=======firstLevolmap:" + firstLevolmap.size());
		System.out.println("=======list:" + list.size());

		System.out.println("=======list:" + list.toString());
		try {
			for (WTPart part1 : list) {
				System.out.println("=========part1:" + part1.getNumber() + "===view:" + part1.getViewName());
				// 取物料的半成品或成品集合
				ArrayList<WTPart> parentslist = firstLevolmap.get(part1);
				System.out.println("=======part1:" + part1.getNumber() + "==" + part1.getViewName() + "====version:"
						+ VersionControlHelper.getIterationDisplayIdentifier(part1).toString());
				if (parentslist != null) {
					for (WTPart showpart : parentslist) {
						String softtype = GenericUtil.getTypeId(showpart);
						String state = showpart.getState().getState().getDisplay(Locale.CHINA);
						if ("废弃".equals(state)) {
							continue;
						}
						System.out.println("====searhMaterialPart  softtype 1111:" + softtype);
						// 如果是成品 直接写值
						if (softtype.indexOf("cn.tianma.FinishedGood") != -1) {
						
							JSONObject object = new JSONObject();
							object.put("Number", "111");
							object.put("view", "111");
							object.put("state", "111");
							String partChildNumber = part1.getNumber();
							String partChildView = part1.getViewName();
							String partParentNumber = showpart.getNumber();
							String partParentView = showpart.getViewName();
							String partParentCustomerName = (String) IBAUtil.getIBAValue(showpart, "customerName");
							String strMesg = partChildNumber + "_" + partChildView + "|" + partParentNumber + ";"
									+ partParentCustomerName;
							System.out.println("====searhMaterialPart  obj 111:" + strMesg);
							array.put(object);
							str.add(strMesg);
						} else {
							System.out.println("====searhMaterialPart  softtype 2222:" + softtype);
							// 半成品 查找是否存在对应的成品
							ArrayList<WTPart> finishedlist = firstLevolmap.get(showpart);

							if (finishedlist != null && finishedlist.size() != 0) {
								// 是否存在成品
								boolean flag = false;
								// 是否已添加
								boolean addflag = false;
								for (WTPart halfpart : finishedlist) {
									String halfsofttype = GenericUtil.getTypeId(halfpart);
									if (halfsofttype.indexOf("cn.tianma.FinishedGood") != -1) {
										flag = true;
										break;
									}
								}
								for (WTPart halfpart : finishedlist) {

									String halfsofttype = GenericUtil.getTypeId(halfpart);
									String halfstate = halfpart.getState().getState().getDisplay(Locale.CHINA);
									if ("废弃".equals(halfstate)) {
										continue;
									}
									JSONObject object = new JSONObject();
									String partChildNumber = part1.getNumber();
									String partChildView = part1.getViewName();

									System.out.println("===halfpart number:" + halfpart.getNumber() + "--view:"
											+ halfpart.getViewName() + "--type:" + halfsofttype);
									// 半成品存在相应的成品时
									if (halfsofttype.indexOf("cn.tianma.FinishedGood") != -1) {
										System.out.println("==========2222222222222222====" + halfpart.getNumber()
												+ "--" + halfpart.getViewName() + "==="
												+ parentslist.contains(halfpart));
										if (!parentslist.contains(halfpart)) {
											// 成品属性
											String partParentNumber = halfpart.getNumber();
											String partParentView = halfpart.getViewName();
											String partParentCustomerName = (String) IBAUtil.getIBAValue(halfpart,
													"customerName");
											// 半成品属性
											 object.put("SemiFinishedGoodNumber", showpart.getNumber());
											 object.put("SemiFinishedGoodVersion", VersionControlHelper
											 .getIterationDisplayIdentifier(showpart).toString());
											 object.put("SemiFinishedGoodView", showpart.getViewName());
											 object.put("StateB",
											 showpart.getState().getState().getDisplay(Locale.CHINA));
											 array.put(object);
											String strMesg = partChildNumber + "_" + partChildView + "|"
													+ partParentNumber + ";" + partParentCustomerName;
											System.out.println("====searhMaterialPart  obj 111:" + strMesg);
											str.add(strMesg);
										}

									} else {
										// 成品属性
										if (!flag) {
											object.put("FinishpartNumber", "");
											object.put("FinishpartVersion", "");
											object.put("FinishpartView", "");
											object.put("StateA", "");

											// 半成品属性
											object.put("SemiFinishedGoodNumber", showpart.getNumber());
											object.put("SemiFinishedGoodVersion", VersionControlHelper
													.getIterationDisplayIdentifier(showpart).toString());
											object.put("SemiFinishedGoodView", showpart.getViewName());
											object.put("StateB",
													showpart.getState().getState().getDisplay(Locale.CHINA));

											array.put(object);
											flag = true;
										}
										// 继续往根节点取成品
										str = FinishedGoodArray(firstLevolmap, array, halfpart, part1);
									}
									System.out.println();
									System.out.println("====searhMaterialPart  obj 222:" + object.toString());
									// break;
								}
							} else if (finishedlist != null && finishedlist.size() == 0) {
								System.out.println("===showpart number:" + showpart.getNumber() + "--view:"
										+ showpart.getViewName() + "--type:" + softtype);

								// 半成品未找到相应的成品
								JSONObject object = new JSONObject();
								object.put("Number", part1.getNumber());
								object.put("PartView", part1.getViewName());
								object.put("State", part1.getState().getState().getDisplay(Locale.CHINA));

								// 成品属性
								object.put("FinishpartNumber", "");
								object.put("FinishpartVersion", "");
								object.put("FinishpartView", "");
								object.put("StateA", "");

								// 半成品属性
								object.put("SemiFinishedGoodNumber", showpart.getNumber());
								object.put("SemiFinishedGoodVersion",
										VersionControlHelper.getIterationDisplayIdentifier(showpart).toString());
								object.put("SemiFinishedGoodView", showpart.getViewName());
								object.put("StateB", showpart.getState().getState().getDisplay(Locale.CHINA));

								array.put(object);

								System.out.println("====searhMaterialPart  obj 333:" + object.toString());
							}

						}
					}
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("========Exception:" + e.getMessage());
		}
//		System.out.println("====MaterialReverseService.searhMaterialPart:" + str.size());
//		System.out.println("====MaterialReverseService.searhMaterialPart:" + str);
		return str;
	}

	

	/**
	 * 取父关系部件集合
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static Map<WTPart, ArrayList<WTPart>> getParentParts3(WTPart part, List<WTPart> list,
			Map<WTPart, ArrayList<WTPart>> firstLevolmap, List<WTPart> partlist) {
		List<WTPart> partlist222 = new ArrayList<WTPart>();
		try {
			// 方法一
			System.out.println("================getParentParts start========== ");
			System.out.println("=====getParentParts part:" + part.getNumber() + "---view:" + part.getViewName());
			QueryResult partsqr = PersistenceHelper.manager.navigate(part.getMaster(), WTPartUsageLink.ALL_ROLES,
					WTPartUsageLink.class, true);
			System.out.println("=====getParentParts partsqr:" + partsqr.size());
			// QueryResult result = PersistenceHelper.manager.navigate(part.getMaster(),
			// WTPartUsageLink.ALL_ROLES,
			// WTPartUsageLink.class);
			// System.out.println("=====Size 1:"+partsqr.size());
			// System.out.println("=====Size 2:"+result.size());
			// QueryResult
			// result=PersistenceHelper.manager.navigate(part,WTPartUsageLink.USES_ROLE,WTPartUsageLink.class,true);

			// 方法二
			// List<WTPart> parentslist = BOMHelp.getWTPartUsageLinkNew(part);
			// 取父关系
			while (partsqr.hasMoreElements()) {
				// for(WTPart partA : parentslist){
				WTPart partA = (WTPart) partsqr.nextElement();
				System.out.println("=====getParentParts partsqr partA:" + partA.getNumber() + "---view:"
						+ partA.getViewName() + "====version:"
						+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString());

				List<WTPart> latestlist = getAllLatestVersionPart(partA.getNumber());

				// 去掉这层循环取得是历史版本
				if (latestlist.contains(partA) && !list.contains(partA) && partA.isLatestIteration()) {
					if (!list.contains(partA) && partA.isLatestIteration()
							&& partA.getViewName().equals(part.getViewName())) {
						String softType = GenericUtil.getTypeId(partA);
						if (softType.indexOf("cn.tianma.FinishedGood") != -1
								|| softType.indexOf("cn.tianma.SemiFinishedGood") != -1) {
							System.out.println("=correct======partA:" + partA.getNumber() + "==" + partA.getViewName()
									+ "====version:"
									+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString()
									+ "===number:" + part.getNumber() + "==view:" + part.getViewName());
							// 已包含 成品或半成品
							if (firstLevolmap.containsKey(part)) {
								System.out.println("containsKey:" + partA.getNumber());
								ArrayList<WTPart> parentparts = firstLevolmap.get(part);
								parentparts.add(partA);
								firstLevolmap.put(part, parentparts);
							} else {
								System.out.println("not containsKey:" + partA.getNumber());
								// 不包含 成品或半成品
								ArrayList<WTPart> childparts = new ArrayList<WTPart>();
								childparts.add(partA);
								firstLevolmap.put(part, childparts);
							}
							partlist222.add(partA);
							// list.add(partA);

							// 递归查询
							// firstLevolmap = getParentParts(partA, list, firstLevolmap,partlist);
						}
						/*
						 * list.add(partA);
						 * 
						 * // 递归查询 getParentParts(partA, list, firstLevolmap,parentlist2);
						 */
					}
				}
			}
			for (WTPart part222 : partlist222) {
				firstLevolmap = getParentParts3(part222, list, firstLevolmap, partlist);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return firstLevolmap;
	}
	
	
	

	@Override
	public FormResult setResultNextAction(FormResult paramFormResult, NmCommandBean paramNmCommandBean,
			List<ObjectBean> paramList) throws WTException {
		System.out.println("start  message====>>>>" + errorMessage);
		FormResult formResult = super.setResultNextAction(paramFormResult, paramNmCommandBean, paramList);
		if (formResult.getStatus().equals(FormProcessingStatus.SUCCESS)) {
			String result = "";
			if (errorMessage.length() > 0) {
				result = errorMessage;
				System.out.println("错误====—>>>" + result);
				result = result.toString();
				formResult.setStatus(FormProcessingStatus.FAILURE);
				result = "<ul >" + result + "</ul>";
				result = "document.getElementById(\"CHECK_RESULT\").innerHTML=\"" + result + "\";alert(\"导出结果已出，请查看\")";
				formResult.setNextAction(FormResultAction.JAVASCRIPT);
				formResult.setJavascript(result);
			} else {
				formResult.setNextAction(FormResultAction.REFRESH_OPENER_AND_SUBMIT_IFRAMES);
			}

		}

		return formResult;
	}
	
}
